﻿using System;
using System.Collections.Generic;
using System.Linq;
using TLang.Values;

namespace TLang.Ast
{
    public class WhileNode : Node
    {
        private readonly List<Node> _elements;


        public WhileNode(List<Node> elements, String file, int start, int end, int line, int col) : base(file, start, end, line, col)
        {
            this._elements = elements;
        }

        public override Value Interp(Scope s)
        {
            Scope scope = new Scope(s);
            Value result = VoidValue.Void;
            while (true)
            {
                Value test = this._elements[0].Interp(scope);
                if (test is BoolValue b)
                {
                    if (b.Value)
                    {
                        for (int i = 1; i < _elements.Count; i++)
                        {
                            if (i == _elements.Count - 1)
                            {
                                result = this._elements[i].Interp(scope);
                            }
                            else
                            {
                                this._elements[i].Interp(scope);
                            }
                        }
                    }
                    else
                    {
                        return result;
                    }
                }
                else
                {
                    throw Util.GeneralError("test result is not BoolValue type");
                }
            }
        }

        public override string ToString()
        {
            return $"({Constants.WhileKeyword} {string.Join(" ", this._elements.Select(a => a.ToString()))})"; ;
        }
    }
}
